<?php

namespace app\admin\controller\bdl\pur;
use app\admin\model\BdOrg;
use app\admin\model\Carinfo;
use app\admin\model\Intentionorderentry;
use app\admin\model\Materialcate;
use app\admin\model\Materialimage;
use app\admin\model\Orderentry;
use app\admin\model\Surface;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Intentionorder extends Backend
{
    /**
     * 模型对象
     * @var \app\admin\model\Intentionorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new \app\admin\model\Intentionorder();
        $this->view->assign("fenableList", $this->model->getFenableList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['modifier','creator','datacenter','forg','customer','address','wxuser'])
                ->where($where)
                ->where('Intentionorder.fenable',"1")
                ->order($sort, $order)
                ->paginate($limit)
            ;



            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 订单操作
     */
    public function action($ids = null)
    {
        $row = $this->model->with(['orderentrynew','orderent','cate'])->find($ids);

        if($this->request->isPost())
        {
            $params = $this->request->post('row/a');

            if($params['fk_bdl_orderstatus'] == 2)
            {

                if(empty($params['fk_bdl_allamount']))
                {
                    $this->error('总金额不能为空');
                }

                if(empty($params['fk_bdl_confirmtime']))
                {
                    $this->error('业务员确认时间不能为空');
                }
            }elseif($params['fk_bdl_orderstatus'] == 1)
            {
                $params['fk_bdl_allamount'] = NULL;
                $params['fk_bdl_confirmtime'] = NULL;
                $params['fk_bdl_auditcomment'] = ' ';

            }




            $params = $this->preExcludeFields($params);
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException()->validate($validate);
                }

                 $row->allowField(true)->save($params);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e)
            {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('操作成功');
        }


        if (!$row) {
            $this->error('信息错误');
        }

        if($row['fk_bdl_ordertype'] ==  1)
        {
            // 准备一个数组来存储分组后的数据
            $groupedInfos = [];

            foreach ($row['orderent'] as $infoson)
            {
                $fk_bdl_bd_surface = $infoson['fk_bdl_bd_surface'];

                if (!isset($groupedInfos[$fk_bdl_bd_surface])) {
                    $groupedInfos[$fk_bdl_bd_surface] = [];
                }

                $groupedInfos[$fk_bdl_bd_surface][] = $infoson->toArray();
            }

            $forg                   = BdOrg::get($row['forgid']);
            $fnumbers               = explode(",",$forg['fk_bdl_mappingorg']);
            $forgids           = BdOrg::whereIn('fnumber',$fnumbers)->where('fk_bdl_bd_datacenter',$row['fk_bdl_bd_datacenter'])->column('id');
            $mater = [];


            foreach ($groupedInfos as $kk=>$vv)
            {
                $surface = $kk;
                $surface = Surface::where('fname',$surface)
                    ->where('forgid','in',$forgids)
                    ->find();
                if(!empty($surface))
                {
                    $surfaceI = Materialimage::where('fk_bdl_bd_surface',$surface['id'])
                        ->find();

                    if(!empty($surfaceI))
                    {
                        $showImageUrl = $surfaceI['fk_bdl_imageurl'];
                    }else{
                        $showImageUrl =  \app\common\model\Config::where('name','noImage')->value('value');
                    }
                }else{
                    $showImageUrl =  \app\common\model\Config::where('name','noImage')->value('value');
                }

                $mater[] = [
                    'fk_bdl_bd_surface' => $kk,
                    'fk_bdl_bd_texture' =>$vv[0]['fk_bdl_bd_texture'],
                    'show_image'        => $showImageUrl,
                    'infos'             => $vv
                ];
            }
            $show_mes['mater'] = $mater;
            $row['show_mes'] = $show_mes;

        }

        $this->assign('row', $row);

        return $this->view->fetch();
    }
}